package com.smasher.weight.base

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import com.smasher.widget.base.BaseActivity

/**
 * @author smasher
 */
abstract class BaseLoongActivity : BaseActivity() {

    override fun initParams(bundle: Bundle?) {
        super.initParams(bundle)
        Log.d(TAG, "initParams: ")
        //requestWriteSettingPermission();
    }


    private var writeCallback: ((Boolean) -> Unit)? = null

    fun requestWriteSettingPermission(callback: (Boolean) -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //版本在23及以上
            if (!Settings.System.canWrite(this)) { //是否有Settings写入权限
                this.writeCallback = callback
                // 以下是请求写入系统设置权限逻辑
                val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS)
                intent.setData(Uri.parse("package:$packageName"))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) //开启一个新activity
                startActivity(intent)
            } else {
                //有了权限，具体的动作
                callback.invoke(true)
            }
        } else{
            // 旧版本，直接执行
            callback.invoke(true)
        }
    }

    private val writeSettingPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                //有了权限，具体的动作
                writeCallback?.invoke(true)
            } else {
                writeCallback?.invoke(false)
            }
        }

    companion object {
        private const val TAG = "BaseInfo"
    }
}
